package com.stylefeng.guns.modular.vpn_push_msg.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.stylefeng.guns.core.base.tips.ErrorTip;
import com.stylefeng.guns.core.base.tips.SuccessTip;
import com.stylefeng.guns.core.common.constant.DatasourceEnum;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.mutidatasource.annotion.DataSource;
import com.stylefeng.guns.modular.system.model.VpnPushMsg;
import com.stylefeng.guns.modular.system.dao.VpnPushMsgMapper;
import com.stylefeng.guns.modular.vpn.dto.PushMsgDTO;
import com.stylefeng.guns.modular.vpn.utils.LogUtil;
import com.stylefeng.guns.modular.vpn_push_msg.service.IVpnPushMsgService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * <p>
 * 消息推送信息表 服务实现类
 * </p>
 *
 * @author stylefeng
 * @since 2020-03-14
 */
@Service
@Slf4j
public class VpnPushMsgServiceImpl extends ServiceImpl<VpnPushMsgMapper, VpnPushMsg> implements IVpnPushMsgService {

    @Autowired
    private VpnPushMsgMapper msgMapper;

    @Value("${push-msg-base-url}")
    private String pushBaseUrl;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 添加推送消息
     * @param pushMsgDTO
     */
    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    @Transactional
    public Long addPushMsg(PushMsgDTO pushMsgDTO) {
        if(StringUtils.isEmpty(pushMsgDTO.getTitle())
                || StringUtils.isEmpty(pushMsgDTO.getContent())){
            throw new GunsException(BizExceptionEnum.VPN_PUSH_MSG_PARAM_ERROR);
        }

        if (pushMsgDTO.getTitle().length() > 30){
            throw new GunsException(BizExceptionEnum.VPN_PUSH_MSG_TITLE_SIZE_TOO_LONG);
        }
        if (pushMsgDTO.getContent().length() > 100){
            throw new GunsException(BizExceptionEnum.VPN_PUSH_MSG_CONTENT_SIZE_TOO_LONG);
        }

        if (pushMsgDTO.getActionFlag().equals("3")){
            if (StringUtils.isEmpty(pushMsgDTO.getLinkUrl())
                    || !Pattern.matches("(http://|https://).*",pushMsgDTO.getLinkUrl())){
                throw new GunsException(BizExceptionEnum.VPN_PUSH_MSG_LINK_ERROR);
            }
        }

        msgMapper.addPushMsg(pushMsgDTO);

        LogUtil.saveOperationLog("添加一条推送消息","消息内容: "+pushMsgDTO.getContent());
        return pushMsgDTO.getId();
    }

    /**
     * 推送消息
     * @param msgId
     */
    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    @Transactional
    public Object pushMsg(Long msgId) {
        try {
            log.info("进入推送消息>>>>>>>>>>>>>>>>>>");
            log.info("msgId =  {} >>>>>>>>>>>>>>>>>>",msgId);
            VpnPushMsg vpnPushMsg = super.baseMapper.selectById(msgId);
            if(vpnPushMsg == null){
                log.info("找不到消息对象 id = {}",msgId);
                throw new GunsException(BizExceptionEnum.VPN_PUSH_MSG_NOT_EXIST);
            }
            String adminToken = redisTemplate.opsForValue().get("adminToken");
            log.info("查询token >>>>>>>>>>>>>>>>>>");
            if(StringUtils.isEmpty(adminToken)){
                log.info("redis 中token为空");
                throw new GunsException(BizExceptionEnum.VPN_API_REDIS_NOT_TOKEN);
            }
            log.info("开始推送消息>>>>>>>>>>>>>>>>>>");
            RestTemplate client = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
            headers.add("token",adminToken);

            String response =
                    client.exchange(pushBaseUrl+"/app/pushid/"+vpnPushMsg.getId()
                            , HttpMethod.GET
                            ,new HttpEntity<>(headers)
                            ,String.class
                            , (Object) null).getBody();

            System.out.println(response);
            log.info("推送消息返回：{}",response);

            JSONObject jsonObject = JSONObject.parseObject(response);

            if(jsonObject.getInteger("code") == 0){
                //推送成功，修改状态为已发送状态
                log.info("推送消息完成，修改消息状态>>>>>>>>>>>>>>>>>>");
                msgMapper.updatePushMsgStatus(vpnPushMsg.getId(),1);
                log.info("修改消息状态结束>>>>>>>>>>>>>>>>>>");

                LogUtil.saveOperationLog("推送消息","推送了一条消息："+vpnPushMsg.getContent());
                return new SuccessTip();
            }else{
                log.info("推送失败>>>>>>>>>>>>>>>>>>");
                throw new GunsException(BizExceptionEnum.VPN_PUSH_MSG_FAIL);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("推送消息出错了 {}",e.getMessage());
            LogUtil.saveOperationLog("推送消息","推送了一条消息，但是失败了");
            throw new GunsException(BizExceptionEnum.VPN_PUSH_MSG_FAIL);
        }
    }

}
